#!/usr/bin/env node

/**
 * 直接修复admin_001的linkedUserId字段
 */

const AdminModel = require('./model/admin_model.js');

async function directFixAdmin() {
    try {
        console.log('=== 直接修复admin_001的linkedUserId字段 ===');
        
        const userId = 'oPOlNvkKFRjdTazLzUq6D2sHunp0'; // 正确的用户ID
        const adminId = 'admin_001';
        
        console.log('用户ID:', userId);
        console.log('Admin ID:', adminId);
        
        // 查找admin记录
        const admin = await AdminModel.getOne({
            ADMIN_ID: adminId
        });
        
        if (!admin) {
            console.log('❌ Admin记录不存在');
            return {
                success: false,
                message: 'Admin记录不存在'
            };
        }
        
        console.log('✅ 找到admin记录:');
        console.log('Admin ID:', admin.ADMIN_ID);
        console.log('当前linkedUserId:', admin.linkedUserId);
        console.log('linkedUserId类型:', typeof admin.linkedUserId);
        console.log('linkedUserId长度:', admin.linkedUserId ? admin.linkedUserId.length : 0);
        
        // 直接更新linkedUserId字段
        await AdminModel.edit({
            ADMIN_ID: adminId
        }, {
            linkedUserId: userId, // 设置为正确的用户ID
            ADMIN_EDIT_TIME: Date.now()
        });
        
        console.log('✅ linkedUserId字段已更新');
        
        // 验证更新结果
        const updatedAdmin = await AdminModel.getOne({
            ADMIN_ID: adminId
        });
        
        console.log('更新后的linkedUserId:', updatedAdmin.linkedUserId);
        console.log('更新后类型:', typeof updatedAdmin.linkedUserId);
        
        // 测试查询
        const testAdmin = await AdminModel.getOne({
            linkedUserId: userId,
            ADMIN_STATUS: 1,
            isActive: true
        });
        
        if (testAdmin) {
            console.log('✅ 查询测试成功：用户已正确关联到admin账号');
            console.log('Admin信息:', {
                adminId: testAdmin.ADMIN_ID,
                adminName: testAdmin.ADMIN_NAME,
                linkedUserId: testAdmin.linkedUserId,
                role: testAdmin.role,
                permissions: testAdmin.permissions
            });
        } else {
            console.log('❌ 查询测试失败');
        }
        
        console.log('\n=== 修复完成 ===');
        
        return {
            success: true,
            message: 'admin_001的linkedUserId字段修复完成',
            userId: userId,
            adminId: adminId
        };
        
    } catch (error) {
        console.error('❌ 修复失败:', error);
        return {
            success: false,
            message: '修复失败: ' + error.message
        };
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    directFixAdmin().then(result => {
        console.log('修复结果:', result);
        process.exit(result.success ? 0 : 1);
    }).catch(error => {
        console.error('脚本执行失败:', error);
        process.exit(1);
    });
}

module.exports = { directFixAdmin };
